package cn.passlink.bletoothchat.BleGATT;

import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattServerCallback;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@SuppressLint("MissingPermission")
public class BleGattServer extends Service {
    private BluetoothDevice device1;
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothManager bluetoothManager;
    private BluetoothGattServer bluetoothGattServer;
    private String name = "www.passlink.cn";

    //发送广播
    private final Intent ClientToServeDataintent = new Intent("com.example.ClientToServeData_DATA_UPDATED");//客户端写操作
    private Intent BleStateIntent = new Intent("BleStateBroadcast");//状态广播

    // 服务uuid
    public static  UUID UUID_SERVER = UUID.fromString("0000fff2-0000-1000-8000-00805f9b34fb");
    // 读的特征值
    public static  UUID UUID_CHAR_READ = UUID.fromString("0000ffe3-0000-1000-8000-00805f9b34fb");
    // 写的特征值
    public static  UUID UUID_CHAR_WRITE = UUID.fromString("0000ffe4-0000-1000-8000-00805f9b34fb");
    private changeBroadcastReceiver receiver;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 获取传递的参数
        if (intent != null && intent.hasExtra("name")) {
            name = intent.getStringExtra("name");
        }
        startAdvertising(name,getApplicationContext());
        // 在这里执行服务的初始化操作
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        // 创建广播接收器实例
        receiver = new changeBroadcastReceiver();
        // 创建意图过滤器，并添加您感兴趣的广播类型
        IntentFilter filter = new IntentFilter();
        //接受写操作
        filter.addAction("cn.passlink.setCharacteristicValue_ACTION");
        // 注册广播接收器
        registerReceiver(receiver, filter);


    }
    /**
     * 创建Ble服务端，接收连接
     */
    public void startAdvertising(String name, Context context) {
        // 初始化蓝牙适配器
        bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        // 检查蓝牙适配器是否为空和是否已启用
        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
        // 检查BluetoothLeAdvertiser是否可用
        if (bluetoothAdapter != null) {
            // BLE广告设置
            AdvertiseSettings settings = new AdvertiseSettings.Builder()
                    .setConnectable(true)
                    .setTimeout(0)
                    .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
                    .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
                    .build();
            AdvertiseData advertiseData = new AdvertiseData.Builder()
                    .setIncludeDeviceName(true)
                    .setIncludeTxPowerLevel(true)
                    .build();
            bluetoothAdapter.setName(name);
            // 开启服务
            BluetoothLeAdvertiser bluetoothLeAdvertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
            if (bluetoothLeAdvertiser != null) {
                bluetoothLeAdvertiser.startAdvertising(settings, advertiseData, advertiseCallback);
            } else {
                Log.d("TAG", "BluetoothLeAdvertiser不可用");
            }
        } else {
            Log.d("TAG", "BluetoothAdapter无法获取！！！");
        }
    }

    /**
     * Ble服务监听
     */
    private final AdvertiseCallback advertiseCallback = new AdvertiseCallback() {
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            super.onStartSuccess(settingsInEffect);
            Log.e("TAG", "服务开启成功 " + settingsInEffect.toString());
            addService();
        }
    };

    /**
     * 添加读写服务UUID，特征值等
     */

    private void addService() {
        BluetoothGattService gattService = new BluetoothGattService(UUID_SERVER, BluetoothGattService.SERVICE_TYPE_PRIMARY);
        // 只读的特征值
        BluetoothGattCharacteristic characteristicRead = new BluetoothGattCharacteristic(UUID_CHAR_READ,
                BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY,
                BluetoothGattCharacteristic.PERMISSION_READ);
        // 只写的特征值
        BluetoothGattCharacteristic characteristicWrite = new BluetoothGattCharacteristic(UUID_CHAR_WRITE,
                BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_READ
                        | BluetoothGattCharacteristic.PROPERTY_NOTIFY,
                BluetoothGattCharacteristic.PERMISSION_WRITE | BluetoothGattCharacteristic.PERMISSION_READ);
        // 将特征值添加至服务里
        gattService.addCharacteristic(characteristicRead);
        gattService.addCharacteristic(characteristicWrite);
        // 监听客户端的连接
        bluetoothGattServer = bluetoothManager.openGattServer(getApplicationContext(), gattServerCallback);
        if (bluetoothGattServer != null) {
            // 添加服务
            bluetoothGattServer.addService(gattService);
        } else {
            Log.d("TAG", "无法打开GattServer！！！");
        }
    }

    private final BluetoothGattServerCallback gattServerCallback = new BluetoothGattServerCallback() {
        @Override
        public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
            super.onConnectionStateChange(device, status, newState);
            device1 = device;
            String state = "";
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                state = "连接成功";
                // 创建意图对象
                BleStateIntent.putExtra("message", "1000");
                // 发送广播
                sendBroadcast(BleStateIntent);
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                state = "连接断开";
            }
            Log.e("TAG", "onConnectionStateChange device=" + device.toString() + " status=" + status + " newState=" + state);
        }

//客户端请求写操作,相当于客户端发送数据给服务端


        @Override
        public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId,
                                                 BluetoothGattCharacteristic characteristic, boolean preparedWrite,
                                                 boolean responseNeeded, int offset, byte[] value) {
            super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value);

            // 判断是否为写特征值
            if (characteristic.getUuid().equals(UUID_CHAR_WRITE)) {
                    // 进行处理
                    String data = new String(value, StandardCharsets.UTF_8);
                    Log.e("TAG", "接收到完整数据：" + data);
                    // 发送消息给视图处理
                    ClientToServeDataintent.putExtra("ClientToServeData", data);
                    sendBroadcast(ClientToServeDataintent);
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                // 发送响应给客户端
                if (responseNeeded) {
                    bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, characteristic.getValue());
                }
            }
        }


    };
    /**
     * 修改服务端特征值
     *
     * @param newValue 要设置的特征值字符串
     */
    public void setCharacteristicValue(String newValue) {
        // 获取服务和特征值
        BluetoothGattService gattService = bluetoothGattServer.getService(UUID_SERVER);
        BluetoothGattCharacteristic characteristicRead = gattService.getCharacteristic(UUID_CHAR_READ);
        // 将字符串转换为字节数组
        byte[] newValueBytes = newValue.getBytes(StandardCharsets.UTF_8);

        // 设置特征值并发送
        Log.d("TAG", "服务端修改了特征值！！！" + newValue);
        characteristicRead.setValue(newValueBytes);
        bluetoothGattServer.notifyCharacteristicChanged(device1, characteristicRead, false);
    }


    public class changeBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("cn.passlink.setCharacteristicValue_ACTION".equals(intent.getAction())) {
                // 处理接收到的广播消息
                String mag=intent.getStringExtra("changeCharcteristic");
                try {
                    setCharacteristicValue(mag);
                }catch (Exception e){
                    Log.e("TAG","没有获取服务，不能发送");
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 取消注册广播接收器
        unregisterReceiver(receiver);
    }
}
